package fem2.observer;

import fem2.Debugger;
import fem2.MaterialModel;
import fem2.Model;
import fem2.Observer;
import fem2.element.StructuralElement;
import fem2.material.ElasticMaterialModel;
import fem2.material.TopOptMaterialModel;

public class StrainEnergyObserver implements Observer {

	private Model m;

	public StrainEnergyObserver(Model m) {
		this.m = m;
		if (!(m.getElement(0) instanceof StructuralElement)) {
			Debugger.error("this observer does not support for this type of model");
		}
	}

	@Override
	public void fireStarted() {
	}

	@Override
	public void fireTimeStepStarted() {
	}

	@Override
	public void fireIterationStarted() {
	}

	@Override
	public void fireIterationFinished() {
		double c = 0.0;
		for (int i = 0; i < m.countElements(); i++) {
			StructuralElement se = (StructuralElement) m.getElement(i);

			MaterialModel mm = se.getMaterialModel();
			if (mm instanceof TopOptMaterialModel) {
				mm = ((TopOptMaterialModel) mm).getNestedMaterialModel();
			}
			if (!(mm instanceof ElasticMaterialModel)) {
				throw new Error("this material model is not supported");
			}
			c += ((ElasticMaterialModel) mm).computeStrainEnergy(se);

		}
		Debugger.watch("Strain energy = " + c);
	}

	@Override
	public void fireTimeStepFinished() {
	}

	@Override
	public void fireFinished() {
	}

}
